import bugtracking.Bug

/**
 * Created by IntelliJ IDEA.
 * User: AlexandruA
 * Date: 6/29/11
 * Time: 12:24 PM
 * To change this template use File | Settings | File Templates.
 */
class IssueGetterImpl implements IssuesGetter {
    /**
     * save issues updated starting with last time update
     * @return
     */
    public void saveIssues() {

        def results = Bug.withCriteria {
            projections {
                max 'delta_ts'
            }
        }
        def date;
        if(results.get(0)!=null){
            date = new Date(results.get(0).getTime());
        } else {
            date = new Date(0)
            Calendar c = Calendar.getInstance();
            c.set(Calendar.YEAR, 2010);
            c.set(Calendar.MONTH, 0);
            c.set(Calendar.DAY_OF_MONTH,1)
            c.set(Calendar.HOUR_OF_DAY,0)
            c.set(Calendar.MINUTE,0)
            date = c.getTime();

        }
        this.saveIssues(date);
        return;
    }

    /**
     * save updated issues starting from specified date till now
     *
     * @param date - the starting date from when to take updated issues
     * @return
     */
    public void saveIssues(Date date) {
        Calendar calendar = Calendar.getInstance();
        def bugzillaDriver = new BugzillaDriver();
        def list = null;
        while(date<calendar.getTime()){
            list = bugzillaDriver.getIssuesUpdatedFrom(date,date+1);
            for( Bug bug: list){
                bug.mergeBug();
            }
            date=date+1;
        }
        return;
    }
}
